import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from 'src/database/prisma.service';
import { CreateUserDto } from './dto/create-user.dto';
import { CreateTokenDto } from './dto/create-token.dto';

@Injectable()
export class UserService {
  constructor(private readonly prismaServer: PrismaService) {}
  async create(user: CreateUserDto) {
    const existingUser = await this.prismaServer.user.findFirst({
      where: { email: user.email },
    });
    if (existingUser) {
      Logger.error(`email already exists`);
      return null;
    }
    return await this.prismaServer.user.create({
      data: { ...user, emailVerified: new Date() },
    });
  }
  async getUserById(id: number) {
    return await this.prismaServer.user.findFirst({ where: { id: id } });
  }
  async getUserByEmail(email: string) {
    Logger.log(`get user by email:${email}`);
    return await this.prismaServer.user.findUnique({ where: { email: email } });
  }
  async getTokenByEmail(email: string) {
    Logger.log(`get token by email ${email}`);
    return await this.prismaServer.verificationToken.findFirst({
      where: { email: email },
    });
  }
  async deleteTokenByEmail(email: string) {
    Logger.log(`delete token for ${email}`);
    const token = await this.prismaServer.verificationToken.findFirst({
      where: { email: email },
    });
    if (!token) {
      Logger.log('toke not found');
      return 'token not found';
    }
    return await this.prismaServer.verificationToken.delete({
      where: { id: token.id },
    });
  }
  async deleteUserById(id:number){
    return this.prismaServer.user.delete({where:{id:id}})
  }
  async createToken(token: CreateTokenDto) {
    Logger.log(`create token ${token.email} ${token.token}`);
    const tokenRst = await this.prismaServer.verificationToken.create({
      data: token,
    });
    if (!tokenRst) {
      return null;
    }
    // get exist user
    const existingUser = await this.getUserByEmail(token.email);
    if (existingUser) {
      return await this.prismaServer.user.update({
        where: { id: existingUser.id },
        data: {
          emailVerified: new Date(),
        },
      });
    }
    return null;
  }
}
